/*
 * 本地存储图片，加快网页加载速度。 
 * 也可以存储其他文件。待研究。
 * update: 2014.05.16
 * @param {string} itemName 设置本地存储时的键名
 * @param {number} holdTime 设置保存的时间长 
 * @param {string} url 需要存储的图片的路径
 * @param {bool} isBackground 是作为背景用(true)，还是图片用(false)
 */

(function( window, undefined ){
  
  "use strict";
  
  var storageImage = function( obj, itemName, holdTime, isBackground ) {
    this.obj = obj;
    this.itemName = itemName;
    this.holdTime = holdTime;
    this.isBackground = isBackground || false;
    this.image = new Image();
    this.image.crossOrigin = "Anonymouse";
    this.init();
  };
  
  storageImage.prototype = {

    storage: function( todaysDate ) {

      var canvas = document.createElement( "canvas" ),
          contxt = canvas.getContext( "2d" );
      
      // 设置canvas和图片的宽高一样
      canvas.width = this.image.width;
      canvas.height = this.image.height;
      
      contxt.drawImage( this.image, 0, 0, this.image.width, this.image.height );
      
      var storaged = {};
      storaged.url = canvas.toDataURL("image/png"),
      storaged.date = todaysDate;
      
      // 保存到本地中，因为存储有5M的大小限制，所以这里使用try catch 会更好
      try {
        localStorage.setItem( this.itemName, JSON.stringify( storaged ) );
      } catch(e) {
        console.log(e);
      }
      
      this.isBackground ? ( this.obj.style.backgroundImage = "url(" + this.image.src + ")" ) : this.obj.setAttribute( "src", this.image.src );
      
    },
    
    storagePrepare: function() {
      
      // 获得现在时间：月份加日期。比如 517
      var date = new Date(),
          todaysDate = ( date.getMonth() + 1 ).toString() + date.getDate().toString();
          
      // 判断是否已经存在此键值
      var localStorageItem = localStorage.getItem( this.itemName );
    
      if( localStorageItem ) {
        
        localStorageItem = JSON.parse( localStorageItem );
        var isExpire = todaysDate*1 - ( localStorageItem.date*1 + this.holdTime ) > 0;
        
        if( isExpire ) {
          // 如果已经过期重新存储
          this.storage( todaysDate );
        } else {
          // 如果没有过期取值
          this.isBackground ? ( this.obj.style.backgroundImage = "url(" + localStorageItem.url + ")" ) : this.obj.setAttribute( "src", localStorageItem.url );
        }
        
      } else {
        
        this.storage( todaysDate );
        
      }
    },
    
    init: function() {
      var _this = this;
      // 获取对象上图片的路径，根据 data-src 属性
      this.image.src = this.obj.getAttribute( "data-src" );
      this.image.addEventListener("load", function() {
        _this.storagePrepare();
      }, false);
    }
  };
  
  if( typeof define === "function" && define.amd ) {
    define( storageImage );
  } else {
    window.storageImage = storageImage;
  }
  
})( window )